package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"homefinder/homefinderrpc/homefinderrpc"
	"homefinder/homefinderrpc/internal/svc"
	"homefinder/model/cache"
	"homefinder/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type HomeListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHomeListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HomeListLogic {
	return &HomeListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HomeListLogic) HomeList(in *homefinderrpc.HomeListRequest) (*homefinderrpc.HomeListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*homefinderrpc.HomeList
	key := fmt.Sprintf("list")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		var err error
		list, err = mysql.ListHome(mysql.DB)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, jsonData, time.Minute*3)
	} else {
		json.Unmarshal([]byte(result), list)
	}

	return &homefinderrpc.HomeListResponse{
		List: list,
	}, nil
}
